<template>
    <m-navbar title="作业详情"/>
    <view class="content-wrap flex-itemsCenter-box flex-wrap">
        <view class="fz-14 w-full">当前科目：{{ homeWorkDetail.courseName }}</view>
        <view class="fz-14 w-full mt-14">发布教师：{{ homeWorkDetail.createNickName || '--' }}</view>
        <view class="fz-14 w-full mt-14">发布时间：{{ homeWorkDetail.createTime }} （{{ homeWorkDetail.week }}）</view>
        <view class="fz-14 w-full mt-14">截至时间：{{ homeWorkDetail.closeTime }} （{{ homeWorkDetail.closeTimeWeek }}）</view>
        <view class="fz-14 w-full mt-14">剩余时间：
            <template v-if="homeWorkDetail.surplusTime > 0">
                {{ homeWorkDetail.surplusTime }} 小时
            </template>
            <template v-else>
                已截止
            </template>
        </view>
        <view class="fz-14 w-full mt-14">作业内容：</view>
        <view class="home-work-box mt-16 w-full rounded-8 flex-justifyBetween-itemsCenter-box box-border px-20 common-shadow">
            <text>{{ homeWorkDetail.homeworkName }}</text>
            <text class="iconfont icon-xiazai text-primary" @click="downloadHomeWork"/>
        </view>
        <view class="fz-14 w-full mt-14">
            <template v-if="homeWorkDetail.surplusTime > 0">
                <view class="mb-14">作业上传：</view>
            </template>
            <template v-if="Boolean(homeWorkDetail.uploadHomeworkUrl)">
                <view class="home-work-box mt-16 w-full rounded-8 flex-justifyBetween-itemsCenter-box box-border px-20 common-shadow">
                    <text class="iconfont icon-zuoyeka text-primary"/>
                    <text>{{ homeWorkDetail.uploadHomeworkName }}</text>
                </view>
            </template>
            <template v-else>
                <template v-if="homeWorkDetail.surplusTime > 0">
                    <uni-section title="选择任意文件" type="line">
                        <view class="example-body">
                            <uni-file-picker
                                v-model="uploadHomeWorkInfo"
                                limit="1"
                                :disabled="homeWorkDetail.surplusTime < 0"
                                :isUpload="Boolean(homeWorkDetail.uploadHomeworkUrl)"
                                file-mediatype="all"
                                @select="select"
                                @delete="deleteHomework"
                            />
                        </view>
                    </uni-section>
                </template>
            </template>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import moment from 'moment'
import uniFilePicker from "@/components/uni-file-picker/uni-file-picker.vue";
import {httpUploadStudentHomeWork} from "@/api/modules/announcement";

const uploadHomeWorkInfo = ref([])
const show = ref(false)

const homeWorkDetail = ref({})

const deleteHomework = (res) => {
    console.log('res', res)
    uploadHomeWorkInfo.value = []
    console.log(uploadHomeWorkInfo.value)
}

const select = (res) => {
    const tempFilePaths = res.tempFilePaths
    uni.uploadFile({
        url: 'https://www.jsjserve.top/prod-api/common/upload',
        filePath: tempFilePaths[0],
        name: 'file',
        header: {
            Authorization: `Bearer ${uni.getStorageSync('token')}`
        },
        success: (uploadFileRes) => {
            const uploadHomeworkUrl = JSON.parse(uploadFileRes.data).url.replace('profile', 'prod-api/profile')
            const uploadHomeworkName = res.tempFiles[0].name
            httpUploadStudentHomeWork({
                id: homeWorkDetail.value.id,
                classId: homeWorkDetail.value.classId,
                courseType: homeWorkDetail.value.courseType,
                uploadHomeworkName,
                uploadHomeworkUrl,
                createUser: homeWorkDetail.value.createUser,
                teacherUploadId: homeWorkDetail.value.id
            }).then(res => {
                if (res.code === 200) {
                    uploadHomeWorkInfo.value = [{
                        name: uploadHomeworkName,
                        url: uploadHomeworkUrl,
                        extname: uploadHomeworkName.split('.')[1]
                    }]
                    homeWorkDetail.value.uploadHomeworkName = uploadHomeworkName
                    homeWorkDetail.value.uploadHomeworkUrl = uploadHomeworkUrl
                    uni.showToast({
                        icon: 'success',
                        title: '作业上传成功！',
                        duration: 2000
                    })
                }
            })
        }
    });
}

const weekDay = (time: string) => {
	const dateList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
	return dateList[new Date(time).getDay()]
}

const downloadHomeWork = () => {
    uni.showLoading({
        title: '下载中...'
    })
	uni.downloadFile({
		url: homeWorkDetail.value.homeworkUrl,
		success: res => {
            console.log('res', res)
			if (res.statusCode === 200) {
                uni.hideLoading()
				uni.saveFile({
					tempFilePath: res.tempFilePath,
					success: saveRes => {
                        console.log(saveRes);
						const savedFilePath = saveRes.savedFilePath
                        if (savedFilePath.indexOf('.png') !== -1) {
                            uni.previewImage({
                                urls: [savedFilePath]
                            })
                        } else {
                            uni.openDocument({
                            	filePath: savedFilePath,
                                showMenu: true
                            })
                        }
					}
				})
			}
		},
        fail: err => {
            console.log(err)
        }
	})
}

const selectSheet = val => {
	if (val.name === '图片') {
		uni.chooseImage({
			count: 6, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success: function(res) {
				console.log(JSON.stringify(res.tempFilePaths))
			}
		})
	} else {
		wx.chooseMessageFile({
			count: 10,
			type: 'file',
			success(res) {
				// tempFilePath可以作为img标签的src属性显示图片
				const tempFilePaths = res.tempFiles
				console.log('tempFilePaths', tempFilePaths)
			}
		})
	}
}

onShow(() => {
	const homeWorkDetailStorage = uni.getStorageSync('homeWorkDetail')

    console.log('homeWorkDetailStorage', homeWorkDetailStorage)
    if (homeWorkDetailStorage.uploadHomeworkUrl) {
        uploadHomeWorkInfo.value = [{
            name: homeWorkDetailStorage.uploadHomeworkName,
            url: homeWorkDetailStorage.uploadHomeworkUrl,
            extname: homeWorkDetailStorage.uploadHomeworkName.split('.')[1]
        }]
    }
    const createTime = homeWorkDetailStorage.createTime
    const closeTime = homeWorkDetailStorage.closeTime
    const surplusTime = moment(new Date(closeTime)).diff(moment(new Date()), 'hours')
	homeWorkDetail.value = {
		...homeWorkDetailStorage,
		week: weekDay(createTime.split(' ')[0]),
		closeTimeWeek: weekDay(closeTime.split(' ')[0]),
        surplusTime
	}
})
</script>

<style scoped lang="scss">
.content-wrap {
    overflow-y: visible;
}

.class-box {
    width: calc(50% - 10rpx);
}

.content-wrap {
    & :nth-child(2n) {
        margin-right: 0;
    }
}

.home-work-box {
    height: 110rpx;
}

.icon-xiazai {
    font-size: 44rpx;
}

.icon-zuoyeka {
    font-size: 80rpx;
}
</style>
